<template>
	<view class="container">
		<!-- 用户信息与房间资产展示 -->
		<view class="combined-section">
			<!-- 用户信息展示 -->
			<view class="info-section">
				<view class="info-item">
					<text class="label">房间号：</text>
					<text class="value">{{ userInfo.ss_mc }}</text>
				</view>
				<view class="info-item">
					<text class="label">入住日期：</text>
					<text class="value">{{ userInfo.checkInDate }}</text>
				</view>
				<view class="info-item">
					<text class="label">到期日期：</text>
					<text class="value">{{ userInfo.checkOutDate }}</text>
				</view>
				<view class="info-item">
					<text class="label">租金：</text>
					<text class="value">{{ userInfo.rentMoney }} 元/月</text>
				</view>
				<view class="info-item">
					<text class="label">押金：</text>
					<text class="value">{{ userInfo.depositMoney }} 元</text>
				</view>
			</view>

			<!-- 房间资产折叠部分 -->
			<view class="dropdown-section">
				<view class="dropdown-toggle" @click="toggleDropdown">
					<view class="toggle-icon">宿舍配置{{ isDropdownOpen ? '↑' : '>' }}</view>
				</view>
				<view class="dropdown-content" v-if="isDropdownOpen">
					<view class="asset-item">
						<text class="asset-label">空调：</text>
						<text class="asset-value"> {{ userInfo.asset1 }} 台</text>
					</view>
					<view class="asset-item">
						<text class="asset-label">洗衣机：</text>
						<text class="asset-value"> {{ userInfo.asset2 }} 台</text>
					</view>
					<view class="asset-item">
						<text class="asset-label">冰箱：</text>
						<text class="asset-value"> {{ userInfo.asset3 }} 台</text>
					</view>
					<view class="asset-item">
						<text class="asset-label">吊风扇：</text>
						<text class="asset-value"> {{ userInfo.asset4 }} 台</text>
					</view>
					<view class="asset-item">
						<text class="asset-label">面积：</text>
						<text class="asset-value"> {{ userInfo.asset10 }} ㎡</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 按钮操作 -->
		<view class="button-section">
			<button class="btn" @click="renewRent">续交租金</button>
			<button class="btn" @click="cancelRent">退租申请</button>
		</view>
	</view>
</template>

<script>
	import {
		ajax
	} from "../../utils/request.js";

	export default {
		data() {
			return {
				userInfo: {
					ss_mc: '',
					rentMoney: 0,
					depositMoney: 0,
					asset1: 0,
					asset2: 0,
					asset3: 0,
					asset4: 0,
					asset10: 0,
					checkInDate: '',
					checkOutDate: ''
				},
				isDropdownOpen: false, // 控制折叠状态
				isUserInfoLoaded: false // 数据是否加载完成
			};
		},
		onLoad() {
			this.getUserInfo();
		},
		methods: {
			ISOToNormal(isoTime) {
				// 将ISO格式的字符串转换为Date对象
				const date = new Date(isoTime);

				// 获取年、月、日、时、分、秒
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要+1
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				const seconds = String(date.getSeconds()).padStart(2, '0');

				// 拼接成易读的格式
				const normalTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
				return normalTime;
			},
			// 获取用户信息
			getUserInfo() {
				// 从本地存储获取 ss_mc 和 account
				const userInfo = uni.getStorageSync('userInfo');
				const ss_mc = userInfo.ss_mc;
				const account = userInfo.account;

				if (!ss_mc || !account) {
					uni.showToast({
						title: '未找到必要的信息',
						icon: 'none'
					});
					return;
				}

				// 调用接口获取用户信息
				ajax('/api/meter/myssinfo', 'POST', {
						ss_mc,
						account
					})
					.then((res) => {
						if (res.success) {
							console.log(res.data.rooms[0]);
							this.userInfo = {
								ss_mc: res.data.rooms[0].ss_mc,
								rentMoney: res.data.rooms[0].rentMoney,
								depositMoney: res.data.rooms[0].depositMoney,
								asset1: res.data.rooms[0].asset1,
								asset2: res.data.rooms[0].asset2,
								asset3: res.data.rooms[0].asset3,
								asset4: res.data.rooms[0].asset4,
								asset10: res.data.rooms[0].asset10,
								checkInDate: this.ISOToNormal(res.data.rooms[0].createdAt),
								checkOutDate: this.ISOToNormal(res.data.rooms[0].updatedAt)
							};
							this.isUserInfoLoaded = true; // 设置数据加载完成
						} else {
							uni.showToast({
								title: '获取用户信息失败',
								icon: 'none'
							});
						}
					})
					.catch((err) => {
						console.error('请求失败:', err);
						uni.showToast({
							title: err.message || '请求失败，请稍后再试',
							icon: 'none'
						});
					});
			},
			// 续交租金
			renewRent() {
				if (!this.isUserInfoLoaded) {
					uni.showToast({
						title: '用户信息加载中，请稍后再试',
						icon: 'none'
					});
					return;
				}

				const total_fee = this.userInfo.rentMoney;
				console.log(total_fee);

				uni.showModal({
					title: '确认续交租金',
					content: `您将续交租金：${total_fee} 元，总计：${total_fee} 元`,
					success: (res) => {
						if (res.confirm) {
							// 调用微信支付
							this.wxPay(total_fee);
						}
					}
				});
			},
			// 微信支付方法（示例，需要根据实际接口调整）
			wxPay(total_fee) {
				// 示例：调用微信支付接口
				uni.login({
					provider: 'weixin',
					success: (loginRes) => {
						if (loginRes.code) {
							console.log('获取到的 code: ' + loginRes.code);
							ajax('/api/wxpay/rentpaywx', 'POST', {
									code: loginRes.code,
									total_fee,
								})
								.then((data) => {
									console.log(data.msg);
									uni.requestPayment({
										provider: 'wxpay',
										timeStamp: String(data.msg.TimeStamp),
										nonceStr: data.msg.nonce_str,
										package: "prepay_id=" + data.msg.responseObject.xml
											.prepay_id._cdata + "",
										signType: 'MD5',
										paySign: data.msg.sign,
										success: (res) => {
											console.log('支付成功:', res);
											uni.showToast({
												title: '支付成功',
												icon: 'success'
											});
										},
										fail: (err) => {
											console.log('支付失败:', err);
											uni.showToast({
												title: '支付失败',
												icon: 'none'
											});
										}
									});
								})
								.catch((error) => {
									console.error('支付接口请求失败:', error);
									uni.showToast({
										title: '支付请求失败',
										icon: 'none'
									});
								});
						} else {
							console.log('登录失败！' + loginRes.errMsg);
							uni.showToast({
								title: '登录失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.log('调用登录接口失败', err);
						uni.showToast({
							title: '调用微信支付失败',
							icon: 'none'
						});
					}
				});
			},
			// 退租申请
			cancelRent() {
				uni.showModal({
					title: '确认退租',
					content: '您确定要退租吗？',
					success: (res) => {
						if (res.confirm) {
							uni.showToast({
								title: '退租成功',
								icon: 'success',
								duration: 2000
							});
						} else if (res.cancel) {
							uni.showToast({
								title: '取消退租',
								icon: 'none',
								duration: 2000
							});
						}
					}
				});
			},
			// 切换折叠状态
			toggleDropdown() {
				this.isDropdownOpen = !this.isDropdownOpen;
			}
		}
	};
</script>

<style>
	.container {
		padding: 20px;
		font-family: "Arial", sans-serif;
		background-color: #f8f8f8;
		position: relative;
	}

	.combined-section {
		background-color: #fff;
		border-radius: 10px;
		padding: 15px;
		margin-bottom: 20px;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
	}

	.info-item,
	.asset-item {
		display: flex;
		justify-content: flex-start;
		align-items: center;
		margin-bottom: 10px;
	}

	.label,
	.asset-label {
		width: 100px;
		color: #666;
		font-size: 16px;
	}

	.value,
	.asset-value {
		flex: 1;
		color: #333;
		font-size: 16px;
	}

	.dropdown-content {
		margin-top: 10px;
		border-radius: 8px;
		padding: 10px;
		box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
	}

	.button-section {
		display: flex;
		justify-content: space-between;
		margin-top: 20px;
	}

	.btn {
		width: 48%;
		height: 40px;
		line-height: 40px;
		text-align: center;
		background-color: #3ba757;
		color: #fff;
		border-radius: 5px;
		font-size: 16px;
		border: none;
		box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
	}

	.btn:active {
		background-color: #348e48;
	}

	.toggle-button {
		position: fixed;
		bottom: 20px;
		right: 20px;
		padding: 10px;
		background-color: #f8f8f8;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
		cursor: pointer;
	}

	.toggle-icon {
		font-size: 13px;
		color: #333;
	}
</style>